//
//  RequestHelper.m
//  Runone
//
//  Created by runone01 on 16/8/10.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "RequestHelper.h"
#import "BCNetAPIClient.h"
#import "MJExtension.h"
#import "AppLocalManager.h"
#import "AppDelegate.h"
#import "HighWayRoadRecord.h"
#import "StationDetailInfo.h"
#import "CameraGunDetailModel.h"
#import "VideoSetting.h"
#import "PileInfo.h"
#import "TableOperation.h"
#import "DeviceBaseInfo.h"
#import "AllLastestVehicleDynamic.h"
#import "UpdateModel.h"
#import "CarListModel.h"
#import "BDVehicleDetailInfo.h"
#import "EventDetailModel.h"
#import "TollEvent.h"
#import "TollStationInfo.h"
#import "ReportEvent.h"
#import "SVProgressHUD.h"
#import "SysPersonalSettingInfoModel.h"
#import "Token.h"
#import "LoginViewController.h"
#import "HighWayRoadRecordRelationInfoListModel.h"
#import "CarManagerModel.h"
#import "LoginViewController.h"

#import "TmepOC.h"
#import "upordown.h"
#import "TempCamera.h"

#import "HighwayMergeRoadRecordModel.h"
#import "HighwayMergeInfoModel.h"
#import "LineMergeJsonModel.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
#import "MergeJsonModel.h"
#import "BDMTollEventTypeDefineInfoModel.h"
#import "BDMTollEventTypeTemplateDefineInfoModel.h"
@interface RequestHelper ()<UIAlertViewDelegate>

@property (nonatomic)BOOL isLogin;
@property(nonatomic,strong)UIAlertView *messageAlert;

@property (nonatomic, strong) RequestGinsengModel *RequestGinseng;

@property(nonatomic,strong)TmepOC *oc;

@property (nonatomic, strong)LoginViewController *loginvc;
@property (nonatomic, strong)UIViewController *passVC;

@end

@implementation RequestHelper

-(void)resultMessage:(NSString *)result {
    _messageAlert =[[UIAlertView alloc] initWithTitle:@"提示" message:result delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_messageAlert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        NSLog(@"取消");
        return;
    }
    else
    {
        NSLog(@"确定");
    }
}

#pragma mark - 去刷新token
-(void)refreshAccessToken:(UIViewController *)passVc{

    //执行网络方法
    NSDictionary *dict=[[NSDictionary alloc] init];
    dict = @{@"refresh_token":GETREFRESH_TOKEN,@"grant_type":@"refresh_token", @"client_id":@"RUNONE",@"client_secret":@"REFRESHTOKEN"};
    
    [[AFHTTPSessionManager manager] POST:GetLOGINURL parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSLog(@"test");
        Token *token=[Token mj_objectWithKeyValues:responseObject];
        [[AppLocalManager sharedManager] saveData:token.access_token andKey:ACCESS_TOKEN];
        [[AppLocalManager sharedManager] saveData:token.refresh_token andKey:REFRESH_TOKEN];
        //        [[BCNetAPIClient sharedJsonClient] setTokenIsOutOf:0];
        [[BCNetAPIClient sharedJsonClient] refreshToken];
        //重新请求
        [self RequestGinsengModel:_RequestGinseng andPushController:passVc];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

//        _loginvc = [[LoginViewController alloc] init];
//        [passVc presentViewController:_loginvc animated:YES completion:nil];
        [self autoLoginAgain];
    }];
}

- (void) autoLoginAgain {
    NSDictionary *dic = [[NSDictionary alloc] init];
    NSString *userNameStr = [[AppLocalManager sharedManager] getDataByKey:@"RememberUserName"];
    NSString *passWordStr = [[AppLocalManager sharedManager] getDataByKey:@"RememberPassWord"];
    dic=@{@"LoginName":userNameStr,@"PassWord":passWordStr,@"SystemCode":DefaultSystemCode ,@"grant_type":@"client_credentials",@"client_id":client_id,@"client_secret":client_secret};
    
    [[AppLocalManager sharedManager] DeleteDataByKey:ACCESS_TOKEN];
    [[BCNetAPIClient sharedJsonClient] requestJsonDataWithPath:GetLOGINURL withParams:dic withMethodType:1 andBlock:^(id data, NSError *error, AFHTTPRequestOperation *operation) {
        if (data) {
//            [[AppLocalManager sharedManager]saveData:userNameStr andKey:@"RememberUserName"];
//            [[AppLocalManager sharedManager]saveData:userNameStr andKey:@"RememberPassWord"];
            Token *token=[Token mj_objectWithKeyValues:data];
            [[AppLocalManager sharedManager] saveData:token.access_token andKey:ACCESS_TOKEN];
            [[AppLocalManager sharedManager] saveData:token.refresh_token andKey:REFRESH_TOKEN];
            [[BCNetAPIClient sharedJsonClient] refreshToken];
            
            [[AppLocalManager sharedManager]saveData:@"1" andKey:@"R"];
        }else {
            _loginvc = [[LoginViewController alloc] init];
            [_passVC presentViewController:_loginvc animated:YES completion:nil];
        
        }
       
    }];
}


-(void)RequestGinsengModel:(RequestGinsengModel *)RequestGinseng andPushController:(UIViewController *)vc {
    _passVC = vc;
    _RequestGinseng = [[RequestGinsengModel alloc] init];
    _RequestGinseng = RequestGinseng;
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic=@{@"methodName":_RequestGinseng.MethodName,@"updatedtime":_RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":_RequestGinseng.DataValue};
    [[BCNetAPIClient sharedJsonClient] requestJsonDataWithPath:RequestGinseng.URL withParams:dic withMethodType:1 andBlock:^(id data, NSError *error, AFHTTPRequestOperation *operation) {
        
        if (data) {
            
            RequestOutginseng *RequestGinsengModel=[RequestOutginseng mj_objectWithKeyValues:data];
            id dataValueModel;
            //取数据成功处理 GetNewAllHighWayRoadInfo
            
            if ([RequestGinsengModel.Code isEqualToString:@"001"]) {
                
                //获取值班站长名字
                if([RequestGinseng.MethodName isEqualToString:@"GetCurrentDutyPersonalName"]) {
                    
                }
                //上下班打卡
                if([RequestGinseng.MethodName isEqualToString:@"SaveSysDutyRecordInfo"])
                {
                    [SVProgressHUD showSuccessWithStatus:@"登记成功"];
                }
                //收费站详情
                if([RequestGinseng.MethodName isEqual:@"GetTollStationDetailInfo"]) {
                    dataValueModel = [self parseJSONByTollStationDetail:RequestGinsengModel.DataValue];
                    //                     [SVProgressHUD showSuccessWithStatus:@"加载收费详情数据完毕"];
                }
                //摄像枪详情
                if([RequestGinseng.MethodName isEqual:@"GetDeviceSettingInfo"]) {
                    dataValueModel = [self parsJSONByCameraGunDetail:RequestGinsengModel.DataValue];
                    
                }
                if ([RequestGinseng.MethodName isEqualToString:@"GetVideoHistorySetting"]) {
                    dataValueModel = [self parsJSONByCameraGunDetail:RequestGinsengModel.DataValue];
                }
                if([RequestGinseng.MethodName isEqualToString:@"ReportConstructionEventDetailInfo"]) {
                    NSLog(@"%@",RequestGinseng.DataValue);
                    [SVProgressHUD showSuccessWithStatus:@"上报数据完毕"];
                }
                // ************************************************** -需要保存的数据Begin-  **************************************************
                //所有高速干道的
                if ([RequestGinseng.MethodName isEqual:@"GetNewAllHighWayRoadInfo"]) {
                    AppDelegate *myDelegate     = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    myDelegate.HighWayRoadArray = [self parsJSONByAllHighWayRoadInfo:RequestGinsengModel.DataValue];
//                    [[TableOperation shareInstance] deleteTable:@"AllNewHighWayRoadTable"];
//                    [[TableOperation shareInstance] creatNewAllHighWayRoadTable];
//                    [self insetDataToHighWayRoadTable:myDelegate.HighWayRoadArray];
//                    NSArray *tempArray = [[TableOperation shareInstance] getNewAllHighWayRoadTable];
//                    NSLog(@"%@",tempArray);
                }
                
                //获取所有收费站信息
                if([RequestGinseng.MethodName isEqual:@"GetAllTollStationInfo"]) {
                    AppDelegate *myDelegate        = (AppDelegate*) [UIApplication sharedApplication].delegate;
                    myDelegate.AllTollStationArray = [StationModel mj_objectArrayWithKeyValuesArray:RequestGinsengModel.DataValue];
//                    myDelegate.AllTollStationArray = [[CoordinateConvertTool sharedCoordinateTool] convertAllStationCoorToMapCoor:array];
                    //                    [[TableOperation shareInstance] createStationTable];
                    //                    [self insertDateToStationTbale:myDelegate.AllTollStationArray];
                    //                    NSArray *tempArray = [[TableOperation shareInstance] getStationTableData];
                    //                    NSLog(@"%@",tempArray);
                }
                //获取所有设备信息表
                if([RequestGinseng.MethodName isEqual:@"GetAllDeviceBaseInfo"]) {
                    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                    //                    myDelegate.AllDeviceBaseArray= [self parseJSONByAllDeviceBase:RequestGinsengModel.DataValue];
                    myDelegate.AllDeviceBaseArray = [DeviceBaseInfo mj_objectArrayWithKeyValuesArray:RequestGinsengModel.DataValue];
                    //                    [[TableOperation shareInstance] deleteTable:@"AllDeviceTable"];
                    //                    [[TableOperation shareInstance] createAllDeviceTable];
                    //                    [self insertDataToDeviceTable:myDelegate.AllDeviceBaseArray];
                    //                    NSArray *tempArray = [[TableOperation shareInstance] getAllDeviceTable];
                    //                    NSLog(@"%@",tempArray);
                }
                //获取所有桩号信表
                if ([RequestGinseng.MethodName isEqualToString:@"GetAllPileInfo"]) {
                    AppDelegate *PirDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                   PirDelegate.PirArray      = [PileInfo mj_objectArrayWithKeyValuesArray:RequestGinsengModel.DataValue];
//                    PirDelegate.PirArray     = [[CoordinateConvertTool sharedCoordinateTool] convertPileNOCoorToMapCoor:array];
                    //                    [[TableOperation shareInstance] createPirNoTable];
                    //                    [self insertDataToPirNoTable:PirDelegate.PirArray];
                    //                    NSArray *tempArray = [[TableOperation shareInstance] getePirNoTable];
                    //                    NSLog(@"%@",tempArray);
                }
                
                
                if ([RequestGinseng.MethodName isEqualToString:@"GetAllTollEventType"]) {
                    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    myDelegate.allTollEvent = [self parsJSONByAllTollEventType:RequestGinsengModel.DataValue];
//                    myDelegate.allTollEvent = [BDMTollEventTypeDefineInfoModel mj_objectArrayWithKeyValuesArray:RequestGinsengModel.DataValue];
                }
                
                // ************************************************** -需要保存的数据End-  **************************************************
                //历史轨迹
                if ([RequestGinseng.MethodName isEqualToString:@"SearchHistoryTrajectory"]) {
                    dataValueModel=[self parsJSONByCarDetail:RequestGinsengModel.DataValue];
                }
                
                
                
            }
            else if([RequestGinsengModel.Code isEqualToString:@"002"])
            {
                NSLog(@"权限不足");
            }
            else if([RequestGinsengModel.Code isEqualToString:@"004"]) {
                AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                myDelegate.HighWayRoadArray= [[TableOperation shareInstance] getNewAllHighWayRoadTable];
                
                AppDelegate *stationDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                stationDelegate.AllTollStationArray= [[TableOperation shareInstance] getStationTableData];
                
                AppDelegate *deviceDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                deviceDelegate.AllDeviceBaseArray= [[TableOperation shareInstance] getAllDeviceTable];
                
                AppDelegate *PirDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                PirDelegate.PirArray= [[TableOperation shareInstance] getePirNoTable];
                
                AppDelegate *carDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
                carDelegate.AllLastestVehicleDynamicArray= [[TableOperation shareInstance] getCarTable];
                
            }
            
            
            
            if (self.block!=nil) {
                self.block(RequestGinsengModel,dataValueModel);
            }
        }
        else if (error) {
            if (error.code==-1001) {
                [SVProgressHUD showSuccessWithStatus:@"网络异常，请稍后再试!"];
            }
            if([operation.responseString isEqualToString:@"401"] ){
                //调用refreshAccesstoken方法，刷新access token。
                [self refreshAccessToken:vc];
            }
        }
        
    }];
    
}

//高速干道信息
- (NSArray *) parsJSONByAllHighWayRoadInfo:(NSString *)dataString {
    NSArray *firstArray = [dataString mj_JSONObject];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (NSDictionary *firstDic in firstArray) {
        
        HighwayMergeRoadRecordModel *recordModel = [[HighwayMergeRoadRecordModel alloc] init];
        recordModel.RoadUID           = firstDic[@"RoadUID"];
        recordModel.SystemUID         = firstDic[@"SystemUID"];
        [[AppLocalManager sharedManager] saveData:recordModel.SystemUID andKey:@"RecordMpo"];
        recordModel.RoadCode          = firstDic[@"RoadCode"];
        recordModel.RoadName          = firstDic[@"RoadName"];
        recordModel.RoadType          = firstDic[@"RoadType"];
        recordModel.BeginPileNo       = firstDic[@"BeginPileNo"];
        recordModel.BeginPileDistance = firstDic[@"BeginPileDistance"];
        recordModel.EndPileNo         = firstDic[@"EndPileNo"];
        recordModel.EndPileDistance   = firstDic[@"EndPileDistance"];
        recordModel.RoadPicUrl        = firstDic[@"RoadPicUrl"];
        NSMutableArray *mergeList     = [[NSMutableArray alloc] init];
        
        for (NSDictionary *mergeDic in [firstDic objectForKey:@"mergeInfoList"]) {
            HighwayMergeInfoModel *infoModel = [[HighwayMergeInfoModel alloc] init];
            infoModel.mergeType = [mergeDic[@"mergeType"] integerValue];
            infoModel.mergeName = mergeDic[@"mergeName"];
            
            if (infoModel.mergeType == 1 || infoModel.mergeType == 0) {
                infoModel.mergeJson = [MergeJsonModel mj_objectWithKeyValues:mergeDic[@"mergeJson"]];
            }
            
            if (infoModel.mergeType == 2) {
                NSMutableArray *mutablearray = [[NSMutableArray alloc] init];
                NSArray *array = [mergeDic[@"mergeJson"] mj_JSONObject];
                for (NSDictionary *dic in array) {
                    LineMergeJsonModel *lineModel = [LineMergeJsonModel mj_objectWithKeyValues:dic];
                    [mutablearray addObject:lineModel];
                }
                infoModel.mergeJsonArray = [mutablearray copy];
            }
            infoModel.UpWayDevices   = [DeviceBaseInfo mj_objectArrayWithKeyValuesArray:mergeDic[@"UpWayDevices"]];//上行设备
            infoModel.DownWayDevices = [DeviceBaseInfo mj_objectArrayWithKeyValuesArray:mergeDic[@"DownWayDevices"]];//下行设备
            [mergeList addObject:infoModel];
        }
        recordModel.mergeInfoList    = [mergeList copy]; //收费站数组
        NSMutableArray *infoArray    = [[NSMutableArray alloc] init];
        NSArray *relationArray       = [firstDic[@"highWayRoadDirectionList"] mj_JSONObject];
        for (NSDictionary *dic in relationArray) {
            HighWayRoadRecordDirectionInfoModel *model = [[HighWayRoadRecordDirectionInfoModel alloc] init];
            model.DirectionUID         = dic[@"DirectionUID"];
            model.RoadUID              = dic[@"RoadUID"];
            model.RoadDirection        = dic[@"RoadDirection"];
            model.DirectionDescription = dic[@"DirectionDescription"];
            model.SystemCode           = dic[@"SystemCode"];
            [infoArray addObject:model];
        }
        recordModel.highWayRoadDirectionList = [infoArray copy];
        [tempArray addObject:recordModel];
    }
    return tempArray;
}

// 收费事件模板
- (NSArray *)parsJSONByAllTollEventType:(NSString *)dataString {
    NSArray *temp = [dataString mj_JSONObject];
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in temp) {
        BDMTollEventTypeDefineInfoModel *model = [[BDMTollEventTypeDefineInfoModel alloc] init];
        model.UID           = dic[@"UID"];
        model.SystemUID     = dic[@"SystemUID"];
        model.TollEventType = [dic[@"TollEventType"] integerValue];
        model.TollEventName = dic[@"TollEventName"];
        model.SystemCode    = dic[@"SystemCode"];
        NSMutableArray *templateArray = [[NSMutableArray alloc] init];
        for (NSDictionary *templateDic in dic[@"TemplateList"]) {
            BDMTollEventTypeTemplateDefineInfoModel *templateModel = [[BDMTollEventTypeTemplateDefineInfoModel alloc] init];
            templateModel.TemplateUID     = templateDic[@"TemplateUID"];
            templateModel.TollEventType   = templateDic[@"TollEventType"];
            templateModel.TemplateName    = templateDic[@"TemplateName"];
            templateModel.TemplateContent = templateDic[@"TemplateContent"];
            [templateArray addObject:templateModel];
        }
        model.TemplateList = [templateArray copy];
        [dataArray addObject:model];
    }
    return dataArray;
}

//两客一危车辆信息
-(NSArray *)parsJSONByGetAllLastestVehicleDynamic:(NSString *)dataValueString {
    NSArray *temp=[dataValueString mj_JSONObject];
    
    NSMutableArray * dataSourceArr=[[NSMutableArray alloc] init];
    for (NSDictionary *dic in temp) {
        AllLastestVehicleDynamic *model = [AllLastestVehicleDynamic mj_objectWithKeyValues:dic];
        
        [dataSourceArr addObject:model];
    }
    return dataSourceArr;
}

-(NSArray *)parseJSONByCarManager:(NSString *)dataValueString {
    NSArray *arr=[dataValueString mj_JSONObject];
    NSMutableArray * dataSourceArr=[[NSMutableArray alloc] init];
    for (NSDictionary *dic in arr) {
        
        CarManagerModel *model=[CarManagerModel mj_objectWithKeyValues:dic];
        [dataSourceArr addObject:model];
    }
    return dataSourceArr;
}

-(TollStationInfo *)parseJSONByTollStationDetailInfo:(NSString *)dataValueString
{
    TollStationInfo *tollStationInfo=[TollStationInfo mj_objectWithKeyValues:dataValueString];
    
    return tollStationInfo;
}


-(NSArray *)parseJSONByAllCurrentEvent:(NSString *)dataValueString {
    NSArray *temp=[dataValueString mj_JSONObject];
    
    NSMutableArray * dataSourceArr=[[NSMutableArray alloc] init];
    for (NSDictionary *dic in temp) {
        CurrentEvent *CEModel=[[CurrentEvent alloc] init];
        CEModel.IncidentUID         = dic[@"IncidentUID"];
        CEModel.SystemUID           = dic[@"SystemUID"];
        CEModel.State               = [dic[@"State"] integerValue];
        CEModel.IncidentType        = [dic[@"IncidentType"] integerValue];
        CEModel.IncidentLevel       = [dic[@"IncidentLevel"] integerValue];
        CEModel.IncidentSource      = dic[@"IncidentSource"];
        CEModel.IncidentDetail      = dic[@"IncidentDetail"];
        CEModel.RecordUserUID       = dic[@"RecordUserUID"];
        CEModel.OccurTime           = dic[@"OccurTime"];
        CEModel.EndTime             = dic[@"EndTime"];
        CEModel.RoadUID             = dic[@"RoadUID"];
        CEModel.RoadDerection       = dic[@"RoadDerection"];
        CEModel.BeginPile           = dic[@"BeginPile"];
        CEModel.EndPile             = dic[@"EndPile"];
        CEModel.Longitude           = dic[@"Longitude"];
        CEModel.Latitude            = dic[@"Latitude"];
        CEModel.RecordTime          = dic[@"RecordTime"];
        CEModel.SystemCode          = dic[@"SystemCode"];
        CEModel.BeginPileDistance   = dic[@"BeginPileDistance"];
        CEModel.EndPileDistance     = dic[@"EndPileDistance"];
        CEModel.IsConfirm           = dic[@"IsConfirm"];
        CEModel.RecordUserName      = dic[@"RecordUserName"];
        CEModel.RecordUserOrgUID    = dic[@"RecordUserOrgUID"];
        CEModel.IncidentParentType  = dic[@"IncidentParentType"];
        [dataSourceArr addObject:CEModel];
    }
    return dataSourceArr;
}


-(StationDetailInfo *)parseJSONByTollStationDetail:(NSString *)dataValueString
{
    StationDetailInfo *stationDetailInfo=[StationDetailInfo mj_objectWithKeyValues:dataValueString];
    return stationDetailInfo;
}

- (CameraGunDetailModel *)parsJSONByCameraGunDetail:(NSString *)dataValueString{
    NSLog(@"%@",dataValueString);
    NSDictionary *dic = [dataValueString mj_JSONObject];
    NSDictionary *DeviceSetting = [[dic objectForKey:@"DeviceData"] mj_JSONObject];
    CameraGunDetailModel *model = [CameraGunDetailModel mj_objectWithKeyValues:DeviceSetting];
    
    return model;
    
}

- (NSMutableArray *)parsJSONByCarDetail:(NSString *)dataValueString{
    NSArray *arr=[dataValueString mj_JSONObject];
    if (arr.count>0) {
        NSMutableArray *carDetail=[[NSMutableArray alloc] init];
        for (NSDictionary *dic in arr) {
            CarListModel *carModel=[CarListModel mj_objectWithKeyValues:dic];
            [carDetail addObject:carModel];
        }
        return carDetail;
    }
    return nil;
    
}

#pragma mark- 事故事件
- (EventDetailModel *)parseJSONByAccidentEventDetailInfo:(NSString *)dataValueString {
    
    NSDictionary *dic=[dataValueString mj_JSONObject];
    NSDictionary *modelDic=dic[@"EventBaseInfo"];
    EventDetailModel *model=[[EventDetailModel alloc]init];
    model.Department  = modelDic[@"Department"];
    model.Header   = modelDic[@"header"];
    model.Telephone = modelDic[@"Telephone"];
    return model;
}
- (EventDetailModel *)parseJSONByConstructionEventDetailInfo:(NSString *)dataValueString {
    
    NSDictionary *dic=[dataValueString mj_JSONObject];
    NSDictionary *modelDic=dic[@"EventBaseInfo"];
    
    EventDetailModel *model=[[EventDetailModel alloc]init];
    model.Department  = modelDic[@"Department"];
    model.Header   = modelDic[@"Header"];
    model.Telephone = modelDic[@"Telephone"];
    //    model.EventDealList =  dic[@"EventDealList"];
    model.Content = dic[@"Content"];
    
    return model;
}
#pragma  mark -  收费事件 (w未解析videosetting 和 pictureSetting)
- (NSArray *)parseJSONByAllTollStationEvent:(NSString *)dataValueString {
    NSArray *temp=[dataValueString mj_JSONObject];
    NSMutableArray *TollStationInfoArray=[[NSMutableArray alloc] init];
    NSMutableArray *dataSource = [[NSMutableArray alloc] init];
    NSMutableArray *tollArray = [[NSMutableArray alloc] init];
    TollStationInfoArray =[temp valueForKey:@"TollStationInfo"];
    
    for (NSDictionary *dic in temp) {
        TollEvent *model       = [[TollEvent alloc] init];
        model.EventUID         = dic[@"EventUID"];
        model.SystemUID        = dic[@"SystemUID"];
        model.TollStationUID   = dic[@"TollStationUID"];
        model.EventType        = [dic[@"EventType"] integerValue];
        model.DutyMonitor      = dic[@"DutyMonitor"];
        model.OccurTime        = dic[@"OccurTime"];
        model.EventDescription = dic[@"EventDescription"];
        model.RecordUserUID    = dic[@"RecordUserUID"];
        model.RecordTime       = dic[@"RecordTime"];
        model.SystemCode       = dic[@"SystemCode"];
        model.TollStationName  = dic[@"TollStationName"];
        
        
        for(NSDictionary *tollStationDic in TollStationInfoArray) {
            TollStationInfo *infoModel   = [[TollStationInfo alloc] init];
            infoModel.TollStationUID     = tollStationDic[@"TollStationUID"];
            infoModel.SystemUID          = tollStationDic[@"SystemUID"];
            infoModel.RoadUID            = tollStationDic[@"RoadUID"];
            infoModel.TollStationName    = tollStationDic[@"TollStationName"];
            infoModel.PileNo             = tollStationDic[@"PileNo"];
            infoModel.PileDistance       = tollStationDic[@"PileDistance"] ;
            infoModel.IsTwoWayPay        = tollStationDic[@"IsTwoWayPaıy"];
            infoModel.Longitude          = tollStationDic[@"Longitude"];
            infoModel.Latitude           = tollStationDic[@"Latitude"];
            infoModel.EntranceLaneCount  = tollStationDic[@"EntranceLaneCount"];
            infoModel.ExitLaneCount      = tollStationDic[@"ExitLaneCount"];
            infoModel.ETCEntranceCount   = tollStationDic[@"ETCEntranceCount"];
            infoModel.ETCExitCount       = tollStationDic[@"ETCExitCount"];
            infoModel.SystemCode         = tollStationDic[@"SystemCode"];
            infoModel.Distance           = tollStationDic[@"Distance"];
            [tollArray addObject:infoModel];
        }
        
        model.TollStationIfo = [tollArray copy];
        [dataSource addObject:model];
    }
    return dataSource;
}

//解析桩号数据
-(NSArray *)parseJSONByAllPirlInfo:(NSString *)dataValueString {
    
    NSArray *temp=[dataValueString mj_JSONObject];
    
    NSMutableArray * dataSourceArr=[[NSMutableArray alloc] init];
    for (NSDictionary *dic in temp) {
        PileInfo *model = [[PileInfo alloc] init];
        //        PileInfo *model = [PileInfo mj_objectWithKeyValues:dic];
        model.PileUID = dic[@"PileUID"];
        model.SystemUID = dic[@"SystemUID"];
        model.RoadUID = dic[@"RoadUID"];
        model.PileNo = dic[@"PileNo"];
        model.Longitude = [dic[@"Longitude"] floatValue];
        model.Latitude = [dic[@"Latitude"] floatValue];
        model.SystemCode = dic[@"SystemCode"];
        model.RoadName = dic[@"RoadName"];
        model.RoadType = [dic[@"RoadType"] integerValue];
        
        model.LeftLongitude = [dic[@"LeftLongitude"] floatValue];;
        model.LeftLatitude = [dic[@"LeftLatitude"] floatValue];
        model.RightLongitude = [dic[@"RightLongitude"] floatValue];;
        model.RightLatitude = [dic[@"RightLatitude"] floatValue];
        NSLog(@"%f,%f,%f,%f",model.LeftLongitude,model.LeftLatitude,model.RightLongitude,model.RightLatitude);
        [dataSourceArr addObject:model];
    }
    return dataSourceArr;
}

- (BDVehicleDetailInfo *)parsJSONByGetBDVehicleDetailInfo:(NSString *)dataValueString {
    
    BDVehicleDetailInfo *bdVehicleDetailInfo = [BDVehicleDetailInfo mj_objectWithKeyValues:dataValueString];
    return bdVehicleDetailInfo;
}


#pragma  mark - 已报事件
- (NSArray *)parseJSONByAllConstructEven:(NSString *)dataValueString {
    NSArray *temp=[dataValueString mj_JSONObject];
    NSMutableArray *dataSoure = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in temp) {
        ReportEvent *reportModel   = [[ReportEvent alloc] init];
        reportModel.IncidentUID    = dic[@"IncidentUID"];
        reportModel.SystemUID      = dic[@"SystemUID"];
        reportModel.RoadUID        = dic[@"RoadUID"];
        reportModel.State          = [dic[@"State"] integerValue];
        reportModel.IncidentType   = [dic[@"IncidentType"] integerValue];
        reportModel.IncidentLevel  = [dic[@"IncidentLevel"] integerValue];
        reportModel.IncidentSource = [dic[@"IncidentSource"] integerValue];
        reportModel.IncidentDetail = dic[@"IncidentDetail"];
        reportModel.RecordUserUID  = dic[@"RecordUserUID"];
        reportModel.OccurTime      = dic[@"OccurTime"];
        reportModel.EndTime        = dic[@"EndTime"];
        reportModel.IsRampFlag     = [dic[@"IsRampFlag"] integerValue];
        reportModel.RoadDerection  = [dic[@"RoadDerection"] integerValue];
        reportModel.BeginPile      = dic[@"BeginPile"];
        reportModel.BeginPileDistance = dic[@"BeginPileDistance"];
        reportModel.EndPile           = dic[@"EndPile"];
        reportModel.EndPileDistance = dic[@"EndPileDistance"];
        reportModel.Longitude       = dic[@"Longitude"];
        reportModel.Latitude        = dic[@"Latitude"];
        reportModel.RecordTime       = dic[@"RecordTime"];
        reportModel.IsConfirm        = dic[@"IsConfirm"];
        reportModel.SystemCode       = dic[@"SystemCode"];
        reportModel.RecordUserName   = dic[@"RecordUserName"];
        reportModel.RecordUserOrgUID = dic[@"RecordUserOrgUID"];
        reportModel.RecordUserOrgName   = dic[@"RecordUserOrgName"];
        
        [dataSoure addObject:reportModel];
    }
    return dataSoure;
}
#pragma mark ----------------------保存到数据库------------------
// 所有道路信息表

//@property (nonatomic, copy) NSString *RoadUID;           //路段流水号
//@property (nonatomic, copy) NSString *SystemUID;         //系统流水号
//@property (nonatomic, copy) NSString *RoadCode;          //干道编号
//@property (nonatomic, copy) NSString *RoadName;          //路段名称
//@property (nonatomic, copy) NSString *RoadType;          //干道类型
//@property (nonatomic, copy) NSString *BeginPileNo;       //开始桩号
//@property (nonatomic, copy) NSString *BeginPileDistance; //开始桩号距离
//@property (nonatomic, copy) NSString *EndPileNo;         //结束桩号
//@property (nonatomic, copy) NSString *EndPileDistance;   //结束桩号距离
//@property (nonatomic, copy) NSArray  *highWayRoadDirectionList; //路段方向列表 HighWayRoadRecordDirectionInfo
//@property (nonatomic, copy) NSArray  *mergeInfoList;

//@property (nonatomic, copy)   NSString *DirectionUID;           // 路段方向流水号
//@property (nonatomic, copy)   NSString *RoadUID;                // 路段流水号
//@property (nonatomic, copy)   NSString *RoadDirection;          // 路段方向值
//@property (nonatomic, copy)   NSString  *DirectionDescription;  // 路段方向描述
//@property (nonatomic, copy)   NSString *SystemCode;             //系统编码


//@property (nonatomic, assign)   NSInteger       mergeType;    //  0起始/结束位置1收费站2交通枢纽
//@property (nonatomic, copy)     NSString        *mergeName;   // 路段流水号
//@property (nonatomic, strong)   MergeJsonModel  *mergeJson;   // 路段方向值
//@property (nonatomic, assign)   NSInteger       Distance;     // 路段方向描述
//
//@property (nonatomic, strong) NSArray  *UpWayDevices;      //上行设备
//@property (nonatomic, strong) NSArray *DownWayDevices;     //下行设备
//@property (nonatomic, strong) NSArray *mergeJsonArray;     //枢纽 //LineMergeJsonModel
- (void)insetDataToHighWayRoadTable:(NSArray *)array {
    NSString *insert = @"insert into AllNewHighWayRoadTable(RoadUID, SystemUID, RoadCode, RoadName, RoadType, BeginPileNo, BeginPileDistance, EndPileNo, EndPileDistance) values(?,?,?,?,?,?,?,?,?)";
    
    for (int i = 0; i < array.count; i ++) {
        HighwayMergeRoadRecordModel *roadModel = array[i];
        
        for (int i = 0; i < roadModel.highWayRoadDirectionList.count; i ++) {
//            HighWayRoadRecordDirectionInfoModel *directionModel = roadModel.highWayRoadDirectionList[i];
//            NSArray *diretArray = @[directionModel.DirectionUID, directionModel.RoadUID, directionModel.RoadDirection, directionModel.DirectionDescription, directionModel.SystemCode];
            
            
        }
        for (int i = 0; i < roadModel.mergeInfoList.count; i++) {
            HighwayMergeInfoModel *mergeModel = roadModel.mergeInfoList[i];
            if (mergeModel.mergeJson) {
                
            }
//            NSArray *mergeArray = @[mergeModel.mergeType, mergeModel.mergeName, mergeModel.Distance];
            
        }
        
        NSArray *param = @[roadModel.RoadUID, roadModel.SystemUID, roadModel.RoadCode, roadModel.RoadName, roadModel.RoadType, roadModel.BeginPileNo, roadModel.BeginPileDistance, roadModel.EndPileNo, roadModel.BeginPileDistance];
        
        [[TableOperation shareInstance] insertDataToTableName:insert Data:param];
    }
    
}

// 收费站表
- (void)insertDateToStationTbale:(NSArray *)stationArray {
    NSString *insert=@"insert into StationTable(TollStationUID, SystemUID, RoadUID, TollStationName, PileNo, PileDistance, IsTwoWayPay, Longitude, Latitude, EntranceLaneCount, ExitLaneCount, ETCEntranceCount, ETCExitCount, SystemCode, Distance) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    
    for (int i = 0; i < stationArray.count; i++) {
        StationModel *model = stationArray[i];
        
        NSString *PileDistance      = [NSString stringWithFormat:@"%ld", (long)model.PileDistance]      ;
        NSString *Longitude         = [NSString stringWithFormat:@"%ld", (long)model.Longitude]         ;
        NSString *Latitude          = [NSString stringWithFormat:@"%ld", (long)model.Latitude]          ;
        NSString *EntranceLaneCount = [NSString stringWithFormat:@"%ld", (long)model.EntranceLaneCount] ;
        NSString *ExitLaneCount     = [NSString stringWithFormat:@"%ld", (long)model.ExitLaneCount]     ;
        NSString *ETCEntranceCount  = [NSString stringWithFormat:@"%ld", (long)model.ETCEntranceCount]  ;
        NSString *ETCExitCount      = [NSString stringWithFormat:@"%ld", (long)model.ETCExitCount]      ;
        NSString *Distance          = [NSString stringWithFormat:@"%ld", (long)model.Distance]          ;
        
        NSArray *param  = @[model.TollStationUID, model.SystemUID, model.RoadUID, model.TollStationName, model.PileNo, PileDistance, model.IsTwoWayPay, Longitude, Latitude, EntranceLaneCount, ExitLaneCount, ETCEntranceCount, ETCExitCount, model.SystemCode, Distance];
        [[TableOperation shareInstance] insertDataToTableName:insert Data:param];
    }
}

// 设备信息表

- (void)insertDataToDeviceTable:(NSArray *)array {
    NSString *Insert = @"insert into AllDeviceTable(DeviceUID, SystemUID,RoadUID,DeviceType,SerialNumber,RegionUID,Direction,PileNo,PileDistance,DeviceMode, Longitude, Latitude, SystemCode,RegionName,Distance, DirectionName) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    
    for (int i=0; i<array.count; i++) {
        DeviceBaseInfo *model =  array[i];
        
        NSString *Longitude    = [NSString stringWithFormat:@"%ld",(long)model.Longitude]   ;
        NSString *Latitude     = [NSString stringWithFormat:@"%ld",(long)model.Latitude]    ;
        NSString *Direction    = [NSString stringWithFormat:@"%ld",(long)model.Direction]   ;
        NSString *DeviceType   = [NSString stringWithFormat:@"%ld",(long)model.DeviceType]  ;
        NSString *PileDistance = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
        
        NSArray *param = @[model.DeviceUID, model.SystemUID, model.RoadUID, DeviceType, model.SerialNumber, model.RegionUID, Direction, model.PileNo, PileDistance, model.DeviceMode, Longitude, Latitude, model.SystemCode, model.RegionName, model.Distance, model.DirectionName];
        
        [[TableOperation shareInstance] insertDataToTableName:Insert Data:param];
    }
}

// 桩号表
- (void)insertDataToPirNoTable:(NSArray *)array {
    NSString *Insert = @"insert into PirNoTable(PileUID, SystemUID,RoadUID,PileNo,Longitude,Latitude,SystemCode,RoadName,RoadType,LeftLongitude,LeftLatitude,RightLongitude,RightLatitude) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
    
    for (int i=0; i<array.count; i++) {
        PileInfo *Model=array[i];
        
        NSString *Longitude=[NSString stringWithFormat:@"%ld",(long)Model.Longitude]            ;
        NSString *Latitude=[NSString stringWithFormat:@"%ld",(long)Model.Latitude]              ;
        NSString *RoadType=[NSString stringWithFormat:@"%ld",(long)Model.RoadType]              ;
        NSString *LeftLongitude = [NSString stringWithFormat:@"%ld",(long)Model.LeftLongitude]  ;
        NSString *LeftLatitude = [NSString stringWithFormat:@"%ld",(long)Model.LeftLatitude]    ;
        NSString *RightLongitude = [NSString stringWithFormat:@"%ld",(long)Model.RightLongitude];
        NSString *RightLatitude = [NSString stringWithFormat:@"%ld",(long)Model.RightLatitude]  ;
        
        NSArray *param=@[Model.PileUID,Model.SystemUID,Model.RoadUID,Model.PileNo,Longitude,Latitude,Model.SystemCode,Model.RoadName,RoadType,LeftLongitude,LeftLatitude,RightLongitude,RightLatitude];
        
        [[TableOperation shareInstance] insertDataToTableName:Insert Data:param];
    }
}


#pragma mark ----------------------更新表------------------
//高速干道信息表
- (void) updateHighWayRoadInfo:(NSArray *)array {
    
    
}

//更新桩号表
-(void)updatePirInfo:(NSArray *)array {
    for (NSDictionary *dic in array)
    {
        PileInfo *model=[PileInfo mj_objectWithKeyValues:dic];
        
        NSString *str=[NSString stringWithFormat:@"update PirNoTable set SystemUID='%@',RoadUID='%@',PileNo='%@',Longitude='%f',Latitude='%f',SystemCode='%@',RoadName='%@',RoadType='%ld',LeftLongitude='%f',LeftLatitude='%f',RightLongitude='%f',RightLatitude='%f' where PileUID='%@'",model.SystemUID,model.RoadUID,model.PileNo,model.Longitude,model.Latitude,model.SystemCode,model.RoadName,(long)model.RoadType,model.LeftLongitude,model.LeftLatitude,model.RightLongitude,model.RightLatitude,model.PileUID];
        
        [[TableOperation shareInstance] updateTable:str];
        NSLog(@"%@",str);
    }
    
}
//更新收费站表

-(void)updateStationTable:(NSArray *)array; {
    for (NSDictionary *dic in array) {
        StationModel *model=[StationModel mj_objectWithKeyValues:dic];
        
        NSString *str=[NSString stringWithFormat:@"update StationTable set SystemUID='%@',RoadUID='%@',TollStationName='%@',PileNo='%@',PileDistance='%ld',IsTwoWayPay='%@',Longitude='%f',Latitude='%ld',EntranceLaneCount='%ld',ExitLaneCount='%ld',ETCEntranceCount='%ld',ETCExitCount='%ld',VideoSetting='%@',SystemCode='%@',Distance='%ld' where TollStationUID='%@'",model.SystemUID,model.RoadUID,model.TollStationName,model.PileNo,(long)model.PileDistance,model.IsTwoWayPay,model.Longitude,(long)model.Latitude,(long)model.EntranceLaneCount,(long)model.ExitLaneCount,(long)model.ETCEntranceCount,(long)model.ETCExitCount,model.VideoSetting,model.SystemCode,(long)model.Distance,model.TollStationUID];
        
        [[TableOperation shareInstance] updateTable:str];
    }
}

//更新设备列表
-(void)updateDeviceTable:(NSArray *)array {
    for (NSDictionary *dic in array) {
        DeviceBaseInfo *model=[DeviceBaseInfo mj_objectWithKeyValues:dic];
        //NSString *UID=[NSString stringWithFormat:@"%@",model.PileUID];
        
        NSString *str=[NSString stringWithFormat:@"update DeviceTable set SystemUID='%@',RoadUID='%@',DeviceType='%ld',SerialNumber='%@',RegionUID='%ld',Direction='%ld',PileNo='%@',PileDistance='%ld',DeviceMode='%ld',Longitude='%ld',Latitude='%ld',DeviceSetting='%ld',SystemCode='%@',RegionName='%@',Distance='%ld' where DeviceUID='%@'",model.SystemUID,model.RoadUID,(long)model.DeviceType,model.SerialNumber,(long)model.RegionUID,(long)model.Direction,model.PileNo,(long)model.PileDistance,(long)model.DeviceMode,(long)model.Longitude,(long)model.Latitude,(long)model.DeviceData,model.SystemCode,model.RegionName,(long)model.Distance,model.DeviceUID];
        
        [[TableOperation shareInstance] updateTable:str];
    }
    
}

-(NSString *)getCurrentTime {
    NSDate *date=[NSDate date];
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *CurrentTime = [format stringFromDate:date];
    return CurrentTime;
}

@end
